<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>管理员列表</el-breadcrumb-item>
    </el-breadcrumb>
    <h1>管理员信息</h1>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入昵称关键字" clearable v-model="name" @clear="searchUser">
            <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" border stripe>
        <el-table-column label="ID" prop="id" :width="50"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="密码" prop="password"></el-table-column>
        <el-table-column label="昵称" prop="name"></el-table-column>
        <!--        <el-table-column label="头像" prop="pic"></el-table-column>-->
        <el-table-column label="性别">
          <template v-slot="scope">
            <span v-text="scope.row.gender === 0?'男':'女'"></span>
          </template>
        </el-table-column>
        <el-table-column label="手机号码" prop="telephone"></el-table-column>
        <el-table-column label="电子邮箱" prop="email"></el-table-column>
        <el-table-column label="角色">
          <template v-slot="scope">
            {{ getRoleNames(scope.row.roles) }}
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <span v-text="scope.row.locked === 0?'正常':'锁定'"></span>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" prop="insertTime"></el-table-column>
        <el-table-column label="更新时间" prop="updateTime"></el-table-column>
        <el-table-column label="操作" :width="130">
          <template v-slot="scope">
            <el-button type="warning" size="small" icon="el-icon-edit" @click="showEditDialog(scope.row)"
                       circle></el-button>
            <span v-if="scope.row.locked === 0">
                <el-button type="primary" size="small" @click="changeLocked(scope.row.id)"
                           icon="el-icon-lock" circle></el-button>
              </span>
            <span v-if="scope.row.locked === 1">
                <el-button type="danger" size="small" @click="changeLocked(scope.row.id)"
                           icon="el-icon-unlock" circle></el-button>
              </span>
            <el-button type="danger" size="small" icon="el-icon-delete"
                       @click="removeUserById(scope.row.id)" circle></el-button>
          </template>
        </el-table-column>

      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[3, 6 , 12, 24]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
    </el-card>

    <!--添加用戶-->
    <el-dialog title="添加用戶" :visible.sync="addDialogVisible"  :close-on-click-modal="false" width="50%">
      <el-form
          :model="addUserForm"
          :rules="addUserFormRules"
          ref="addUserFormRef"
          label-width="100px"
          class="demo-ruleForm"
      >
        <el-form-item label="用戶名" prop="username" >
          <el-input v-model="addUserForm.username" @blur="judgedSameName(addUserForm.username)"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="addUserForm.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="telephone">
          <el-input v-model="addUserForm.telephone"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="addUserForm.gender" placeholder="请选择性别">
            <!----value需要绑定----->
            <el-option label="男" :value="0"></el-option>
            <el-option label="女" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="addUserForm.roleIds" multiple placeholder="请选择角色">
            <el-option :label="item.name" :value="item.id" v-for="item in roleList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addUser">确 定</el-button>
        <el-button @click="resetAddUser">重 置</el-button>
      </span>
    </el-dialog>

    <!--修改用戶-->
    <el-dialog
        title="修改用戶"
        :visible.sync="editDialogVisible"
        width="50%"
        :close-on-click-modal="false"
        :before-close="editUserFormClose"
    >
      <el-form
          :model="editUserForm"
          :rules="editUserFormRules"
          ref="editUserFormRef"
          label-width="100px"
          class="demo-ruleForm"
      >
        <el-form-item label="用户ID" prop="id">
          <el-input v-model="editUserForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="用戶名" prop="username">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="editUserForm.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="telephone">
          <el-input v-model="editUserForm.telephone"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="editUserForm.gender" placeholder="请选择性别">
            <!----value需要绑定----->
            <el-option label="男" :value="0"></el-option>
            <el-option label="女" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="editUserForm.roleIds" multiple placeholder="请选择角色">
            <el-option :label="item.name" :value="item.id" v-for="item in roleList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editUser">确 定</el-button>
        <el-button @click="editUserFormClose">取 消</el-button>
      </span>
    </el-dialog>
    <h1>我的团队相关信息</h1>
    <Team></Team>
  </div>
</template>
<script>
import Team from "@/backend/system/Team.vue";
export default {
  components:{Team},
  data() {
    return {
      pageNum: 1,
      pageSize: 3,
      userList: [],
      roleList: [],
      roleIds: [], //存储选中的h角色ID
      total: 0,
      name: "",
      flag:false,
      //添加
      addDialogVisible: false,
      addUserForm: {
        username: "",
        password: "",
        name: "",
        telephone: "",
        email: "",
        gender: 0,
        roleIds: [],
      },
      //修改
      editDialogVisible: false,
      editUserForm: {
        id: -1,
        username: "",
        password: "",
        name: "",
        telephone: "",
        email: "",
        gender: 0,
        roleIds: [],
      },
      //修改验证
      editUserFormRules: {
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/, message: "密码至少包含 数字和英文，长度6-20", trigger: "blur"},
        ],
        name: [
          {required: true, message: "请输入昵称", trigger: "blur"},
          {pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]{2,10}$/, message: "昵称由中文字母或数字组成，长度2~10位", trigger: "blur"}
        ],
        telephone: [
          {required: true, message: "请输入手机号", trigger: "blur"},
          {
            pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
            message: "手机号码不符合规则！",
            trigger: "blur"
          }
        ],
        email: [
          {required: true, message: "请输入邮箱账号", trigger: "blur"},
          {pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: "邮箱账号不符合规则！", trigger: "blur"}
        ],
        roleIds: [
          {required: true, message: "请选择角色", trigger: "change"},
        ],
      },
      //添加验证
      addUserFormRules: {
        username: [
          {validator: (rule, value, callback) => {
              let reg = /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/;
              if (!value) {
                callback(new Error('用户名为必填项'));
              } else if (value.length < 4 || value.length > 10) {
                callback(new Error('长度在 4 到 10 个字符'));
              } else if (!reg.test(value)) {
                callback(new Error('姓名不支持特殊字符'));
              } else if (this.flag) {
                callback(new Error('用户名已存在'));
              } else {
                callback();
              }}
            , trigger: 'blur' },
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/, message: "密码至少包含 数字和英文，长度6-20", trigger: "blur"},
        ],
        name: [
          {required: true, message: "请输入昵称", trigger: "blur"},
          {pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]{2,10}$/, message: "昵称由中文字母或数字组成，长度2~10位", trigger: "blur"}
        ],
        telephone: [
          {required: true, message: "请输入手机号", trigger: "blur"},
          {
            pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
            message: "手机号码不符合规则！",
            trigger: "blur"
          }
        ],
        email: [
          {required: true, message: "请输入邮箱账号", trigger: "blur"},
          {pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: "邮箱账号不符合规则！", trigger: "blur"}
        ],
        roleIds: [
          {required: true, message: "请选择角色", trigger: "change"},
        ],
      }
    };
  },
  methods: {
    judgedSameName(username){
      let url='/manager/judgedSameName';
      console.log(username)
      this.$axios.get(url,{
        params: {userName:username}
      }).then(res=>{
        if(res.data.code===201){
          console.log(res.data.msg);
         this.flag=true;
        }else {
          this.flag=false;
        }
      })
    },
    getRoleNames(list) {
      let info = '';
      if (list != null && list.length > 0) {
        for (let r of list) {
          info += r.name + ","
        }
      }
      return info.substring(0, info.length - 1);
    },
    changeLocked(id) {
      let url = "/manager/changeLocked/" + id;
      this.$axios.put(url).then(res => {
        this.message(res);
      })
    },
    //删除
    async removeUserById(id) {
      this.$confirm('此操作将永久删除该本用户, 是否继续?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '不是',
        type: 'warning'
      }).then(() => {
        let url = '/manager/delete/' + id;
        this.$axios.delete(url).then(res => {
          this.message(res);
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    //显示修改表单
    showEditDialog(row) {
      let temp = [];
      for (let r of row.roles) {
        temp.push(r.id);
      }
      this.editUserForm = row;
      this.editUserForm.roleIds = temp;
      this.editDialogVisible = true;
    },
    //关闭表单
    editUserFormClose() {
      this.$confirm('此操作将不保存修改内容, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'info',
          message: '已取消修改'
        });
        this.editDialogVisible = false;
        this.$refs.editUserFormRef.resetFields();
      }).catch(() => {
      });
    },
    //修改管理员
    editUser() {
      this.$refs.editUserFormRef.validate(valid => {
        if (!valid) {
          return;
        } else {
          let url = "/manager/edit";
          this.$axios.put(url, this.editUserForm)
              .then(res => {
                this.message(res);
                this.editDialogVisible = false;
                this.initUser();
              })
        }
      })
    },
    //添加管理员
    addUser() {
      this.$refs.addUserFormRef.validate(valid => {
        if (!valid) {
          return;
        } else {
          let url = "/manager/add";
          this.$axios.post(url, this.addUserForm)
              .then(res => {
                this.message(res);
                this.addDialogVisible = false;
                this.initUser();
              })
        }
      })
    },
    //重置添加管理员表单
    resetAddUser() {
      this.$refs.addUserFormRef.resetFields();
      this.roleIds = [];
    },

    searchUser() {
      this.pageNum = 1;
      this.initUser();
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.pageNum = 1;
      this.initUser();
    },
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.initUser();
    },
    //初始化查询 用户信息
    initUser() {
      let url = "/manager/list";
      this.$axios.get(url, {
        params: {
          now: this.pageNum,
          size: this.pageSize,
          name: this.name
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.userList = res.data.data.list;
          this.pageSize = res.data.data.pageSize;
          this.pageNum = res.data.data.pageNum;
          this.total = res.data.data.total;
        } else {
          this.$message({
            type: 'error',
            message: res.data.msg,
            duration: 1000
          })
        }
      })
    },
    //初始化查询 所有角色
    initRole() {
      let url = "/role/showAllRole";
      this.$axios.get(url).then(res => {
        if (res.data.code === 200) {
          this.roleList = res.data.data;
        } else {
          this.$message({
            type: 'error',
            message: res.data.msg,
            duration: 1000
          })
        }
      })
    },
    message(res) {
      if (res.data.code === 200) {
        this.$message({
          type: 'success',
          message: res.data.msg,
          duration: 1000
        });
        this.initUser();
      } else {
        this.$message({
          type: 'error',
          message: res.data.msg,
          duration: 1000
        })
      }
    }
  },
  created() {
    this.initUser();
    this.initRole();
  }
};
</script>
<style lang="less" scoped>
</style>